package com.huangsm.juc.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 1.ReadWriteLock:读写锁
 * 写写/读写
 * 读读不互斥
 * @author huangsm
 * @version V1.0
 */
public class TestReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo rw = new ReadWriteLockDemo();
        new Thread(() -> {
            rw.set((int) Math.random());
        }, "write").start();
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                rw.get();
            }
        }, "read").start();
    }
}

class ReadWriteLockDemo {
    private int num = 0;
    /**
     * 读写锁
     */
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 读取数据
     */
    public void get() {
        lock.readLock().lock();//上锁
        try {
            System.out.println(Thread.currentThread().getName() + ":" + num);
        } finally {
            lock.readLock().unlock();

        }
    }

    /**
     * 写
     *
     * @param num
     */
    public void set(int num) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName());
            this.num = num;
        } finally {
            lock.writeLock().unlock();
        }
    }
}